var fs = require('fs')
var cmd = require('node-cmd')

console.log('开始打包...')
cmd.get('yarn build', function () {
  console.log('打包完成，移动文件并修改php模板')
  exists('./dist/static', '../dstcSrv/public/static', copy)

  var css = fs.readdirSync('./dist/static/css')[0]
  var app, manifest, vendor

  fs.readdirSync('./dist/static/js').forEach(item =>{
    if(/^app/.test(item)) app = item
    if(/^manifest/.test(item)) manifest = item
    if(/^vendor/.test(item)) vendor = item
  })

  const indexPhp = '../dstcSrv/resources/views/h5/index.blade.php'
  var content = fs.readFileSync(indexPhp).toString()
  fs.writeFileSync(indexPhp, content.replace(/asset\('(.+)'\)/g, function(s, s1){
    const base = s1.replace(/^(.+?)[^\/]+$/, '$1')
    if(/^\/static\/css\/app/.test(s1)) return `asset('${base + css}')`
    if(/^\/static\/js\/app/.test(s1)) return `asset('${base + app}')`
    if(/^\/static\/js\/manifest/.test(s1)) return `asset('${base + manifest}')`
    if(/^\/static\/js\/vendor/.test(s1)) return `asset('${base + vendor}')`
  }))

  console.log('完成')
})

var fs = require('fs'),
stat = fs.stat;

function copy(src, dst) {
  // 读取目录中的所有文件/目录
  fs.readdir(src, function (err, paths) {
    if (err) {
      throw err;
    }

    paths.forEach(function (path) {
      var _src = src + '/' + path,
        _dst = dst + '/' + path,
        readable, writable;

      stat(_src, function (err, st) {
        if (err) {
          throw err;
        }

        // 判断是否为文件
        if (st.isFile()) {
          // 创建读取流
          readable = fs.createReadStream(_src);
          // 创建写入流
          writable = fs.createWriteStream(_dst);
          // 通过管道来传输流
          readable.pipe(writable);
        }
        // 如果是目录则递归调用自身
        else if (st.isDirectory()) {
          exists(_src, _dst, copy);
        }
      });
    });
  });
};

// 在复制目录前需要判断该目录是否存在，不存在需要先创建目录
function exists(src, dst, callback) {
  fs.exists(dst, function (exists) {
    // 已存在
    if (exists) {
      callback(src, dst);
    }
    // 不存在
    else {
      fs.mkdir(dst, function () {
        callback(src, dst);
      });
    }
  });
};